<?php

namespace app\common\model\tableField;

use app\utils\business\BaseModel;
use think\Model;

class TableFieldEnumModel extends BaseModel
{
    protected $table = 'yoshop_table_field_enum';
    public static function init()
    {
        parent::init();
        TableFieldEnumModel::afterWrite(function ($model) {
            /**
             * 更新 表字段枚举数据 缓存
             * @var Model $model 模型数据
             */
            static::cacheTableFieldEnumList($model->getAttr('table_name'), $model->getAttr('field_name'));
        });
    }
    
    /**
     * 关联 表字段枚举 分组
     * @return \think\model\relation\BelongsTo
     */
    public function tableFieldEnumGroupModel(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(TableFieldEnumGroupModel::class,'group_tag', 'group_tag');
    }
    
    /**
     * 获取 某个 表字段枚举 的 中文释义
     * @param string $tableName
     * @param string $fieldName
     * @param string|int $value
     * @return int|string
     */
    public static function getExplainCn(string $tableName, string $fieldName, $value)
    {
        $tableFieldEnumList = static::getTableFieldEnumList($tableName, $fieldName);
        return $tableFieldEnumList[$value]['explain_cn'] ?? $value;
    }
    
    /**
     * 获取 表字段枚举列表
     * @param string $tableName 表名
     * @param string $fieldName 字段名
     * @return array
     */
    public static function getTableFieldEnumList(string $tableName, string $fieldName): array
    {
        $tableFieldEnumList = cache('getTableFieldEnumList_' . $tableName . '_' . $fieldName);
        if (empty($tableFieldEnumList)) {
            $tableFieldEnumList = static::cacheTableFieldEnumList($tableName, $fieldName);
        }
        return $tableFieldEnumList;
    }
    
    
    /**
     * 缓存 表字段枚举数据
     * @param string $tableName 表名
     * @param string $fieldName 字段名
     * @return array
     */
    public static function cacheTableFieldEnumList(string $tableName, string $fieldName): array
    {
        $cacheTableFieldEnumList = static::where('table_name', '=', $tableName)
            ->where('field_name', '=', $fieldName)
            ->column('*', 'value');
        cache('getTableFieldEnumList_' . $tableName . '_' . $fieldName, $cacheTableFieldEnumList);
        return $cacheTableFieldEnumList;
    }
    
}